package com.jic.market.impl.allocation;

import com.jic.market.entity.AllocationModel;
import com.jic.market.common.enums.PromotionAllocationStrategyEnum;
import com.jic.market.request.after.TellAddAllocationRequest;
import com.jic.market.service.AllocationService;
import com.jic.market.service.allocation.PromotionAddAllocationStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xuyongliang
 * @version V1.0
 * @className PromotionAddAllocationStrategyContext
 * @description TODO
 * @date 2020/3/16
 */
@Slf4j
@Component
public class PromotionAddAllocationStrategyContext {

    @Resource
    private AllocationService allocationService;
    /**
     *使用线程安全的ConcurrentHashMap存储所有实现Strategy接口的Bean
     *key:beanName
     *value：实现Strategy接口Bean
     */
    private final Map<String, PromotionAddAllocationStrategy> strategyMap = new ConcurrentHashMap<>();

    @Autowired
    public PromotionAddAllocationStrategyContext(Map<String, PromotionAddAllocationStrategy> strategyMap) {
        this.strategyMap.clear();
        strategyMap.forEach((k, v)-> this.strategyMap.put(k, v));
    }

    /**
     * 添加分摊信息
     * @param tellRequest   会员等级
     * @return              分摊id
     */
    public Long addAllocation(TellAddAllocationRequest tellRequest) {
        log.info("--------进入分摊策略上下文tellRequest--{}-----",tellRequest);
        String value = PromotionAllocationStrategyEnum.getValue(tellRequest.getPromType());
        AllocationModel allocationModel = strategyMap.get(value).collectionAllocation(tellRequest);

        if(allocationModel!=null){
            //将分摊实体转成存入表中
            allocationService.allocationAdd(allocationModel);
            return allocationModel.getId();
        }
        return null;
    }

}
